<template>
    <div class="app-container">
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span class="card-title">数据集管理</span>
                <el-button type="primary" icon="el-icon-plus" style="float: right" @click="showCreateDialog">
                    新建数据集
                </el-button>
            </div>

            <!-- 筛选栏 -->
            <div class="filter-container">
                <el-input v-model="listQuery.name" placeholder="数据集名称" style="width: 200px" class="filter-item"
                    @keyup.enter.native="handleFilter" />
                <el-select v-model="listQuery.status" placeholder="验证状态" clearable class="filter-item"
                    style="width: 150px">
                    <el-option label="已验证" value="verified" />
                    <el-option label="未验证" value="unverified" />
                    <el-option label="已失效" value="invalid" />
                </el-select>
                <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                    搜索
                </el-button>
                <el-button class="filter-item" plain icon="el-icon-refresh" @click="resetQueryForm">
                    重置
                </el-button>
            </div>

            <!-- 数据集表格 -->
            <el-table v-loading="listLoading" :data="filteredDatasets" border fit highlight-current-row
                style="width: 100%">
                <el-table-column label="ID" prop="id" align="center" width="80" />
                <el-table-column label="数据集名称" prop="name" align="center" min-width="180" />
                <el-table-column label="描述" prop="description" align="center" min-width="220" />
                <el-table-column label="训练样本" prop="train_samples" align="center" width="150">
                    <template slot-scope="{row}">
                        <el-tag>{{ row.train_samples | numberFormat }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="验证样本" prop="val_samples" align="center" width="150">
                    <template slot-scope="{row}">
                        <el-tag>{{ row.val_samples | numberFormat }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="类别数" prop="num_classes" align="center" width="150">
                    <template slot-scope="{row}">
                        <el-tag>{{ row.num_classes | numberFormat }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="状态" prop="status" align="center" width="120">
                    <template slot-scope="{row}">
                        <el-tag :type="statusType[row.status]">
                            {{ row.status | statusFilter }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="created_time" width="300" align="center" />
                <el-table-column label="操作" align="center" width="300">
                    <template slot-scope="{row}">
                        <el-button-group>
                            <el-tooltip content="验证数据集" placement="top">
                                <el-button type="primary" icon="el-icon-check" size="mini" @click="handleVerify(row)" />
                            </el-tooltip>
                            <el-tooltip content="下载数据集" placement="top">
                                <el-button type="success" icon="el-icon-download" size="mini"
                                    @click="handleDownload(row)" />
                            </el-tooltip>
                            <el-tooltip content="编辑信息" placement="top">
                                <el-button type="warning" icon="el-icon-edit" size="mini" @click="handleEdit(row)" />
                            </el-tooltip>
                            <el-tooltip content="删除数据集" placement="top">
                                <el-button type="danger" icon="el-icon-delete" size="mini"
                                    @click="handleDelete(row.id)" />
                            </el-tooltip>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                background @pagination="getList" style="margin-top: 20px">
            </el-pagination>
        </el-card>

        <!-- 数据集表单对话框 -->
        <el-dialog :title="dialogTitleMap[dialogStatus]" :visible.sync="dialogVisible" width="650px" @close="resetForm">
            <el-form ref="dataForm" :model="tempDataset" :rules="rules" label-width="120px" label-position="right">
                <el-form-item label="数据集名称" prop="name">
                    <el-input v-model="tempDataset.name" />
                </el-form-item>
                <el-form-item label="数据集描述" prop="description">
                    <el-input v-model="tempDataset.description" type="textarea" :rows="3" placeholder="请输入数据集描述信息" />
                </el-form-item>
                <el-form-item v-if="dialogStatus === 'create'" label="数据集文件" prop="zipFile" class="upload-item">
                    <el-alert title="请上传YOLO数据集标注格式的ZIP文件" description="" type="warning" show-icon>
                    </el-alert>
                    <el-upload ref="upload" :auto-upload="false" :limit="1" :file-list="fileList"
                        :on-change="handleFileChange" accept=".zip" drag
                        action="https://jsonplaceholder.typicode.com/posts/">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">
                            将ZIP文件拖到此处，或<em>点击上传</em>
                        </div>
                        <div slot="tip" class="el-upload__tip">
                            请上传包含训练集和验证集的ZIP压缩包，目录结构应符合规范
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" :loading="submitLoading"
                    @click="dialogStatus === 'create' ? createDataset() : updateDataset()">
                    确认
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import api from '@/api/dataset'

export default {
    name: 'DatasetManage',
    filters: {
        statusFilter(status) {
            const statusMap = {
                verified: '已验证',
                unverified: '未验证',
                invalid: '无效'
            }
            return statusMap[status]
        },
        numberFormat(num) {
            return num ? num.toLocaleString() : 0
        }
    },
    data() {
        return {
            // 查询相关参数
            listQuery: {
                page: 1,
                limit: 10,
                name: '',
                status: ''
            },
            //分页器相关
            total: 0,
            // 表格相关
            listLoading: false,
            filteredDatasets: [],
            statusType: {
                verified: 'success',
                unverified: 'info',
                invalid: 'danger'
            },
            // 对话框相关
            dialogVisible: false,
            dialogStatus: '',
            dialogTitleMap: {
                create: '创建数据集',
                update: '编辑数据集'
            },
            tempDataset: {
                id: undefined,
                name: '',
                description: '',
                zipFile: null
            },
            rules: {
                name: [
                    { required: true, message: '数据集名称不能为空', trigger: 'blur' },
                    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
                ],
                zipFile: [
                    { required: true, message: '请上传数据集文件', trigger: 'change' }
                ]
            },
            fileList: [],
            submitLoading: false
        }
    },
    created() {
        this.getList()
    },
    methods: {
        // 获取数据集列表
        getList() {
            this.listLoading = true
            api.fetchDatasets(this.listQuery)
                .then(res => {
                    // 正确获取响应数据
                    this.filteredDatasets = res.data.items
                    this.total = res.data.total
                })
                .catch(error => {
                    this.$message.error('获取数据集失败: ' + error.message)
                    console.error('API Error:', error.response || error)
                })
                .finally(() => {
                    this.listLoading = false
                })
        },
        // 显示创建对话框
        showCreateDialog() {
            this.dialogStatus = 'create'
            this.dialogVisible = true
        },

        // 处理文件选择
        handleFileChange(file) {
            this.tempDataset.zipFile = file.raw
        },

        // 创建数据集
        async createDataset() {
            this.$refs['dataForm'].validate(async valid => {
                if (valid) {
                    this.submitLoading = true
                    try {
                        const formData = new FormData()
                        formData.append('name', this.tempDataset.name)
                        formData.append('description', this.tempDataset.description)
                        formData.append('file', this.tempDataset.zipFile)
                        // 调用API创建数据集
                        await api.createDataset(formData)
                        // 重置表单
                        this.resetForm()
                        this.dialogVisible = false
                        // 更新页面数据
                        this.getList()
                        this.$message.success('数据集创建成功')
                    } finally {
                        this.submitLoading = false
                    }
                }
            })
        },
        // 重置表单
        resetForm() {
            this.$refs['dataForm'].resetFields()
            this.fileList = []
        },
        // 处理筛选操作
        handleFilter() {
            this.listQuery.page = 1 // 搜索时重置到第一页
            this.getList()
        },
        // 重置查询表单
        resetQueryForm() {
            this.listQuery = {
                page: 1,
                limit: 10,
                name: '',
                status: ''
            }
            this.getList()
        },
        // 验证数据集
        handleVerify(row) {
            this.$confirm('此操作将验证数据集的完整性, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                api.verifyDataset(row.id).then(res => {
                    // this.$message.success('数据集验证成功')
                    this.$notify({
                        title: '验证成功',
                        message: `数据集"${row.name}"验证成功`,
                        type: 'success'
                    });
                    this.getList()
                }).catch(error => {
                    this.$message.error('数据集验证失败: ' + error.message)
                })
            })
        },
        // 下载数据集处理逻辑
        handleDownload(row) {
            api.downloadDataset(row.id)
                .then(response => {
                    // console.log(response)//前端response对象不含content-disposition
                    // 通过HTTP状态码判断成功
                    if (response.status === 200) {
                        // 获取Content-Disposition头
                        const contentDisposition = response.headers['content-disposition']

                        // 安全解析文件名
                        let filename = `dataset_${row.name}.zip` // 默认文件名
                        if (contentDisposition) {
                            const match = contentDisposition.match(/filename\*?=(?:UTF-8'')?"?([^"]+)"?/i)
                            if (match && match[1]) {
                                filename = decodeURIComponent(match[1])
                            } else {
                                const simpleMatch = contentDisposition.match(/filename="?([^"]+)/i)
                                if (simpleMatch && simpleMatch[1]) {
                                    filename = simpleMatch[1]
                                }
                            }
                        }

                        // 创建下载链接
                        const blob = new Blob([response.data])
                        const url = window.URL.createObjectURL(blob)
                        const link = document.createElement('a')
                        link.href = url
                        link.download = decodeURIComponent(filename)
                        link.click()

                        // 清理资源
                        URL.revokeObjectURL(url)
                    }
                })
                .catch(error => {
                    // 处理JSON格式的错误响应
                    if (error.response?.data?.code) {
                        const reader = new FileReader()
                        reader.onload = () => {
                            try {
                                const errData = JSON.parse(reader.result)
                                this.$message.error(`下载失败: ${errData.error}`)
                            } catch (e) {
                                this.$message.error('未知错误格式')
                            }
                        }
                        reader.readAsText(error.response.data)
                    } else {
                        this.$message.error('服务器连接异常')
                    }
                })
        },
        //编辑数据集
        handleEdit(row) {
            this.tempDataset = Object.assign({}, row)
            this.dialogStatus = 'update'
            this.dialogVisible = true
        },
        //编辑数据集
        updateDataset() {
            api.updateDataset(this.tempDataset.id, this.tempDataset).then(res => {
                this.$message.success('更新成功')
                // 更新页面
                this.getList()
                this.dialogVisible = false
            }).catch(error => {
                this.$message.error('更新失败: ' + error.message)
            })
        },
        // 删除数据集
        handleDelete(id) {
            this.$confirm('此操作将永久删除该数据集, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                api.deleteDataset(id)
                    .then(() => {
                        this.$message.success('删除成功')
                        this.getList()
                    })
                    .catch(error => {
                        this.$message.error('删除失败: ' + error.message)
                    })
            }).catch(() => {
                this.$message.info('已取消删除')
            })
        },

    }
}
</script>

<style scoped>
.upload-item ::v-deep .el-upload-dragger {
    width: 480px;
    height: 180px;
}

.filter-item {
    margin: 10px;
}
</style>